package trading_strategy.events;

import java.util.concurrent.*;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 6 mai 2010
 * Time: 17:31:12
 * To change this template use File | Settings | File Templates.
 */
public class EventDispatcher {
    Executor executor;
    String name;
    private long nextEventTs;

    public EventDispatcher(final String name) {
        this.name = name;
        executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new PriorityBlockingQueue<Runnable>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, name);
            }
        });
    }

    public void addEvent(TimedRunnable runnable) {
        executor.execute(runnable);
    }

    public abstract static class TimedRunnable implements Runnable, Comparable {
        long ts;

        public TimedRunnable(long ts) {
            this.ts = ts;
        }

        @Override
        public int compareTo(Object o) {
            if (o instanceof TimedRunnable) {
                TimedRunnable to = (TimedRunnable) o;
                if (ts > to.ts) {
                    return 1;
                } else if (ts < to.ts) {
                    return -1;
                }
                if (this != o) {
                    return 1;
                }
            }
            return 0;
        }
    }
}
